import 'dart:async';

import 'package:ad_common/third_ad.dart';
import 'package:ad_common/third_ad_instance.dart';
import 'package:ad_common/util/log.dart';
import 'package:anythink_sdk/at_index.dart';
import 'package:top_on_ad_plugin/top_on_base_ad.dart';

/// FileName top_on_banner_ad
/// @Author zhuqingfang
/// @Date 2022/9/30 3:31 下午
/// @Description top on banner ad
//ad request map
Map<String, TopOnBannerAd> _bannerAdRequest = {};

//ad loaded map
Map<String, TopOnBannerAd> _bannerAdLoaded = {};

//ad show object
TopOnBannerAd? _bannerAdShow;
//为空初始化，不空，不初始化，确保listener只注册一次
StreamSubscription? _initBannerAdListener;

class TopOnBannerAd extends TopOnBaseAd {
  TopOnBannerAd({required ThirdAdParams thirdAdParams})
      : super(thirdAdParams: thirdAdParams);

  @override
  void load() {
    //在父类执行top on sdk 初始化
    super.load();

    //注册监听广告回调，只初始化一次
    _initBannerAdListener = _initBannerAdListener ?? _bannerAdListener();

    //检查当前placementId对应的广告状态
    checkAdState(
        thirdAdType: ThirdAdType.topOnBannerAd,
        placementId: thirdAdParams.placementId,
        isLoaded: (isLoaded) {
          if (isLoaded == true) {
            //如果对应的placementId 有对应的广告缓存，不再请求广告
            thirdAdParams.thirdAdEventCallback(
                AdCallbackEvent.loadFail,
                '${thirdAdParams.placementId} top on banner ad is loading',
                {thirdAdParams.placementId: 'isLoading'});
          } else {
            //一个 placementId 对应一个实例，缓存起来，只有真正发起广告请求的时候才缓存
            _bannerAdRequest[thirdAdParams.placementId] = this;
            //请求广告
            _loadBannerAd(thirdAdParams: thirdAdParams);
          }
        });
  }

  @override
  void show() {
    //判读广告是否可展示
    isShowTopOnAd(
        thirdAdType: ThirdAdType.topOnBannerAd,
        placementId: thirdAdParams.placementId,
        isShowAd: (isShowAd) {
          if (isShowAd == true) {
            if (_bannerAdLoaded.containsKey(thirdAdParams.placementId)) {
              _bannerAdShow = _bannerAdLoaded[thirdAdParams.placementId];
            }
            //获取banner widget
            thirdAdParams.bannerParams?.thirdBannerAdOutputWidget =
                PlatformBannerWidget(thirdAdParams.placementId);

            //已获取第三方广告banner widget 通知业务刷新UI，展示广告
            thirdAdParams.thirdAdEventCallback(
                AdCallbackEvent.renderSuccess,
                '${thirdAdParams.placementId} top on banner ad widget get',
                null);
          } else {
            //广告没准备好，无法展示
            Map<String, Object> infoMap = {
              thirdAdParams.placementId: 'notReady'
            };
            thirdAdParams.thirdAdEventCallback(
                AdCallbackEvent.showFail,
                '${thirdAdParams.placementId} top on banner ad is notReady',
                infoMap);
          }
        });
  }
}

//请求banner广告
_loadBannerAd({required ThirdAdParams thirdAdParams}) {
  if(thirdAdParams.bannerParams!.adaptiveOrientation == null) {
    ATBannerManager.loadBannerAd(
        placementID: thirdAdParams.placementId,
        extraMap: {
          ATCommon.getAdSizeKey(): ATBannerManager.createLoadBannerAdSize(
              thirdAdParams.bannerParams!.width,
              thirdAdParams.bannerParams!.height)
        });
  }else {
    //自适应，仅针对admob平台
    ATBannerManager.loadBannerAd(
        placementID: thirdAdParams.placementId,
        extraMap: {
          ATCommon.getAdSizeKey(): ATBannerManager.createLoadBannerAdSize(
              thirdAdParams.bannerParams!.width,
              thirdAdParams.bannerParams!.height),
          ATBannerManager.getAdaptiveWidthKey(): thirdAdParams.bannerParams!.width,
          ATBannerManager.getAdaptiveOrientationKey(): thirdAdParams.bannerParams!.adaptiveOrientation!.value
        });
  }
}

//检查banner广告状态信息
_checkBannerAdStatus({required String placementId}) {
  return ATBannerManager.checkBannerLoadStatus(placementID: placementId);
}

_getBannerValidAds({required String placementId}) {
  ATBannerManager.getBannerValidAds(placementID: placementId).then(
      (value) => Log.i('banner ad $placementId all available ad info:$value'));
}

StreamSubscription _bannerAdListener() {
  return ATListenerManager.bannerEventHandler.listen((value) async {
    switch (value.bannerStatus) {
      //广告加载失败
      case BannerStatus.bannerAdFailToLoadAD:
        Log.i(
            "flutter bannerAdFailToLoadAD ---- placementID: ${value.placementID} ---- errStr:${value.requestMessage}");
        if (_bannerAdRequest.containsKey(value.placementID)) {
          Map<String, Object> infoMap = {value.placementID: 'loadFail'};
          _bannerAdRequest[value.placementID]?.thirdAdParams.thirdAdEventCallback(
              AdCallbackEvent.loadFail,
              'top on banner ad placementID :${value.placementID} load fail errStr:${value.requestMessage}',
              infoMap);
        }
        break;
      //广告加载成功
      case BannerStatus.bannerAdDidFinishLoading:
        Log.i(
            "flutter bannerAdDidFinishLoading ---- placementID: ${value.placementID}");
        if (_bannerAdRequest.containsKey(value.placementID)) {
          _bannerAdLoaded[value.placementID] =
              _bannerAdRequest[value.placementID]!;
          final adState =
              await _checkBannerAdStatus(placementId: value.placementID);
          _bannerAdLoaded[value.placementID]
              ?.thirdAdParams
              .thirdAdEventCallback(
                  AdCallbackEvent.loadSuccess,
                  'top on banner ad placementID:${value.placementID}  loaded',
                  adState['adInfo']);
        }
        _getBannerValidAds(placementId: value.placementID);
        break;
      //广告自动刷新成功
      case BannerStatus.bannerAdAutoRefreshSucceed:
        Log.i(
            "flutter bannerAdAutoRefreshSucceed ---- placementID: ${value.placementID} ---- extra:${value.extraMap}");
        break;
      //广告被点击
      case BannerStatus.bannerAdDidClick:
        Log.i(
            "flutter bannerAdDidClick ---- placementID: ${value.placementID} ---- extra:${value.extraMap}");
        _bannerAdShow?.thirdAdParams.thirdAdEventCallback(
            AdCallbackEvent.onClick,
            'top on banner ad placementID:${value.placementID}  onClick',
            value.extraMap);
        break;
      //Deeplink
      case BannerStatus.bannerAdDidDeepLink:
        Log.i(
            "flutter bannerAdDidDeepLink ---- placementID: ${value.placementID} ---- extra:${value.extraMap} ---- isDeeplinkSuccess:${value.isDeeplinkSuccess}");
        break;
      //广告展示成功
      case BannerStatus.bannerAdDidShowSucceed:
        Log.i(
            "flutter bannerAdDidShowSucceed ---- placementID: ${value.placementID} ---- extra:${value.extraMap}");
        _bannerAdShow?.thirdAdParams.thirdAdEventCallback(
            AdCallbackEvent.onShow,
            'top on banner ad placementID:${value.placementID}  onShow',
            value.extraMap);
        break;
      //广告关闭按钮被点击
      case BannerStatus.bannerAdTapCloseButton:
        Log.i(
            "flutter bannerAdTapCloseButton ---- placementID: ${value.placementID} ---- extra:${value.extraMap}");
        _bannerAdShow?.thirdAdParams.thirdAdEventCallback(
            AdCallbackEvent.onClose,
            'top on banner ad placementID:${value.placementID}  onDismiss',
            value.extraMap);
        break;
      //广告自动刷新失败
      case BannerStatus.bannerAdAutoRefreshFail:
        Log.i(
            "flutter bannerAdAutoRefreshFail ---- placementID: ${value.placementID} ---- errStr:${value.requestMessage}");
        break;
      case BannerStatus.bannerAdUnknown:
        Log.i("flutter bannerAdUnknown");
        break;
    }
  });
}
